from django.shortcuts import render, HttpResponse
from django.db.models import Avg, Count, Max, Min, Sum, F, Q
from .models import Book, Author, Publisher, BookOrder
# Create your views here.
def avg_view(request):
    result = Book.objects.aggregate(avg_price=Avg('price'))
    print(result)
    return HttpResponse("avg view")
def count_view(request):
    result = Book.objects.aggregate(book_count=Count('price'))
    print(result)
    return HttpResponse("count view")
def max_min_view(request):
    result = Book.objects.aggregate(max_age=Max('price'),min_age=Min('price'))
    print(result)
    return HttpResponse("max view and min view")
# aggregate()方法可以同时计算多个聚合函数,annotate()对聚合函数进行分组
# annotate可以根据主键算指定书的销售额，aggregare则是不区分哪本书是哪本数，单纯算出所有书的销售总额
def sum_view(request):
    result = Book.objects.annotate(sum_price=Sum("price")).values('title', 'sum_price')
    print(result)
    return HttpResponse("sum view")
# F表达式的使用
def f_view(request):
    Book.objects.update(price=F('price')+10)
    return HttpResponse("f view")

def q_view(request):
    books = Book.objects.filter(Q(price__gte=107) | Q(rating__gte=8)).all()
    for book in books:
        print(book.title, book.price, book.rating)
    return HttpResponse("q view")
